import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class OrderTraversal {
    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
        TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
 }
    //非递归（迭代）遍历

    public List<Integer> preorderTraversal(TreeNode root) {
        if(root == null){
            return new ArrayList<>();
        }
        List<Integer> arraylist = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(!stack.isEmpty() || cur != null){
            while(cur != null){
                stack.push(cur);
                arraylist.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return arraylist;
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        if(root == null){
            return new ArrayList<>();
        }
        List<Integer> arrayList = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()){
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            arrayList.add(top.val);
            cur = top.right;
        }
        return arrayList;
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        if(root == null){
            return new ArrayList<>();
        }
        List<Integer> arraylist = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while(!stack.isEmpty() || cur != null){
            while(cur != null ){
                stack.push(cur);

                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right != null && top.right != prev){

                cur = top.right;
            }else{
                TreeNode top2 = stack.pop();
                arraylist.add(top2.val);
                cur = null;
                prev = top2;
            }

        }
        return arraylist;
    }
}
